package com.qing.design.patterns.iterator.example.social_networks;

import com.qing.design.patterns.iterator.example.iterators.FacebookIterator;
import com.qing.design.patterns.iterator.example.iterators.ProfileIterator;
import com.qing.design.patterns.iterator.example.profile.Profile;

import java.util.ArrayList;
import java.util.List;

public class Facebook implements SocialNetwork{


	private List<Profile> profiles;

	public Facebook(List<Profile> cache) {
		//TODO 判空操作十分高效，避免空指针异常
		if(cache!=null){
			this.profiles=cache;
		}else{
			this.profiles=new ArrayList<>();
		}
	}

	public Profile requestProfileFromFacebook(String profileEmail){
	//这里有一个对Facebook API端点之一的POST请求。
	//相反，我们模拟长网络连接，这是您所期望的
	//在现实生活中。。。
		//TODO 拆分代码粒度更小，可重复使用
		simulateNetworkLatency();
		System.out.println("Facebook: Loading profile '" + profileEmail + "' over the network...");

		return  findProfile(profileEmail);
	}


	public List<String> requestProfileFriendsFromFacebook(String profileEmail,String contactType){
		simulateNetworkLatency();
		System.out.println("Facebook: Loading '" + contactType + "' list of '" + profileEmail + "' over the network...");

		Profile profile=findProfile(profileEmail);
		if(profile!=null){
			return profile.getContacts(contactType);
		}
		return null;
	}


	@Override
	public ProfileIterator createFriendsIterator(String profileEmail) {
		return new FacebookIterator(this,"friends",profileEmail);
	}

	@Override
	public ProfileIterator createCoworkersIterator(String profileEmail) {
		return new FacebookIterator(this,"coworkers",profileEmail);
	}


	private Profile findProfile(String profileEmail){
		for (Profile profile : profiles) {
			if(profile.getEmail().equals(profileEmail)){
				return profile;
			}
		}

		System.out.println("----------------没有该用户---------------");
		return null;
	}

	//模拟工作状态
	private void simulateNetworkLatency(){
		try {
			Thread.sleep(2500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
